﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;

namespace Wsq.Utils.DoNetFramework40.Socket
{
    public class Client
    {
        /// <summary>  
        /// 客户端连接  
        /// </summary>
        public delegate void OnClientConnected();
        /// <summary>  
        /// 客户端连接断开
        /// </summary>
        public delegate void OnClientDisConnected(String message);
        /// <summary>  
        /// 接收到客户端的数据  
        /// </summary>  
        /// <param name="token">客户端</param>  
        /// <param name="buff">客户端数据</param>  
        public delegate void OnReceiveData(byte[] buff);

        public event OnClientConnected onClientConnected;
        public event OnClientDisConnected onClientDisConnected;
        public event OnReceiveData onReceiveData;

        private string IP = "127.0.0.1";
        private int PORT = 9527;
        private System.Net.Sockets.Socket _clientSocket = null;
        private byte[] _buffer = null;
        public Client(string ip, int port)
        {
            IP = ip;
            PORT = port;
        }
        public bool Initialize()
        {
            _clientSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _buffer = new byte[1024];
            IPAddress ip = IPAddress.Parse(IP);
            IPEndPoint endPoint = new IPEndPoint(ip, PORT);
            try
            {
                _clientSocket.Connect(endPoint);
                //Console.WriteLine(string.Format("连接{0}服务器成功!", _clientSocket.LocalEndPoint.ToString()));
                if (onClientConnected!=null)
                {
                    onClientConnected();
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine(string.Format("连接服务器失败:\n" + ex.Message));
                if (onClientDisConnected != null)
                {
                    onClientDisConnected(ex.Message);
                }
                return false;
            }
            //开线程接收服务器下来的数据
            Thread receiveThread = new Thread(OnReceiveMsg);
            receiveThread.IsBackground = true;
            receiveThread.Start();
            return true;
        }

        /// <summary>
        /// 接收服务器消息
        /// </summary>
        private void OnReceiveMsg()
        {
            while (true)
            {
                try
                {
                    int receiveLen = _clientSocket.Receive(_buffer);
                    if (receiveLen==0)
                    {
                        if (onClientDisConnected != null)
                        {
                            onClientDisConnected("服务器主动断开");
                        }
                        break;
                    }
                    //string receiveMsg = Encoding.UTF8.GetString(_buffer, 0, receiveLen);
                    //Console.WriteLine(string.Format("收到服务器消息:" + receiveMsg));
                    byte[] data=new byte[receiveLen];
                    Array.Copy(_buffer, 0, data, 0, receiveLen);
                    if (onReceiveData != null)
                    {
                        onReceiveData(data);
                    }
                }
                catch (Exception ex)
                {
                    //Console.WriteLine("接收消息异常:\n" + ex.Message);
                    _clientSocket.Shutdown(SocketShutdown.Both);
                    _clientSocket.Dispose();
                    if (onClientDisConnected != null)
                    {
                        onClientDisConnected(ex.Message+"|"+ex.StackTrace);
                    }
                    break;
                }
            }
            
        }

        /// <summary>
        /// 给服务器发消息
        /// </summary>
        public void SendMsg(byte[] msg)
        {
            if (_clientSocket != null && _clientSocket.Connected)
            {
                _clientSocket.Send(msg);
            }
        }
    }

}
